#include "Head.h"
#include <math.h>
using namespace sf;

Head::Head(Vector2f position, Vector2f size, Color color, float speed, Vector2f direction) {
	shape = Shape::Circle(Vector2f(0, 0), 1, color);
	shape.SetScale(size);
	shape.Move(position);
	this->moveSpeed = speed;
	this->direction = direction;
	turningLeft = turningRight = false;
	turnSpeed = 90;
	alive = true;
	turning = false;
//	tail.initialize(calculateTailDockingPosition(), size.x, direction);
}

void Head::update(float deltaTime) {
	if (!alive) {
		return;
	}
	float rotation = 0.0f;
	if (turningLeft) {
		rotation = turnSpeed;
	}
	if (turningRight) {
		rotation = -turnSpeed;
	}
	turningLeft = turningRight = false;
	rotation *= deltaTime;
	Matrix3 rotate;
	rotate.SetFromTransformations(Vector2f(0, 0), Vector2f(0, 0), rotation, Vector2f(1, 1));
	direction = rotate.Transform(direction);
	Vector2f toMove = direction * moveSpeed * deltaTime;
	shape.Move(toMove);
//	tail.addTailPiece(calculateTailDockingPosition(), shape.GetScale().x, direction);
}

void Head::render(RenderWindow& renderWindow) {
	renderWindow.Draw(shape);
	renderWindow.Draw(getCollisionShape());
}

Shape Head::getCollisionShape() const {
	Shape collisionShape;
	collisionShape.SetCenter(shape.GetCenter());
	collisionShape.SetScale(shape.GetScale());
	collisionShape.SetPosition(shape.GetPosition());
	collisionShape.SetColor(Color::Red);
	for (unsigned int i = 0; i < shape.GetNbPoints(); i++) {
		if (getSmallAngle(shape.GetPointPosition(i), direction) <= M_PI / 4) {
			collisionShape.AddPoint(shape.GetPointPosition(i));
		}
	}
	return collisionShape;
}

void Head::computeCollision(EnumerationCollisionTypes collisionTypes) {
	switch (collisionTypes) {
	case TAIL:
	case HEAD:
	case WALL:
		alive = false;
		break;
	}
}

void Head::turnLeft() {
	turningLeft = true;
	turningRight = false;
}

void Head::turnRight() {
	turningLeft = false;
	turningRight = true;
}

bool Head::isAlive() const {
	return alive;
}

Color Head::getColor() {
	return shape.GetPointColor(0);
}

Shape Head::getNewTailPiece() {
	Shape shape = tail.getNewTailPiece();
	shape.SetColor(getColor());
	return shape;
}

Vector2f Head::calculateTailDockingPosition() {
	return shape.GetPosition();
}
